<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <div v-show="!switchFlag">
                <Row class="query-form2">
                  <i-col span="8">
                    <FormItem label="二级集团：" prop="order">
                      <two-level-org org-code v-model="form1.twoLevelOrgId" ></two-level-org>
                    </FormItem>
                  </i-col>
                  <i-col span="8">
                    <!--                        <FormItem label="排查人：">-->
                    <!--                            <Input v-model="form1.screenUserName" placeholder="请输入排查人"/>-->
                    <!--                        </FormItem>-->
                    <FormItem label="排查公司：">
                      <company-select v-model="form1.screenOrgName"></company-select>
                    </FormItem>
                  </i-col>
                    <Col span="8">
                        <div style="float: right;">
                            <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
                        </div>
                    </Col>
                </Row>
            </div>
            <div v-show="switchFlag">
                <Row :model="form1" class="query-form2">
                  <i-col span="8">
                    <FormItem label="二级集团：" prop="order">
                      <two-level-org org-code v-model="form1.twoLevelOrgId" ></two-level-org>
                    </FormItem>
                  </i-col>
                  <i-col span="8">
                    <!--                        <FormItem label="排查人：">-->
                    <!--                            <Input v-model="form1.screenUserName" placeholder="请输入排查人"/>-->
                    <!--                        </FormItem>-->
                    <FormItem label="排查公司：">
                      <company-select v-model="form1.screenOrgName"></company-select>
                    </FormItem>
                  </i-col>
                    <Col span="8">
                        <FormItem label="排查状态：">
                            <Select v-model="form1.taskStatus">
                                <Option value="1">未排查</Option>
                                <Option value="2">已排查</Option>
                            </Select>
                        </FormItem>
                    </Col>

                </Row>
                <Row class="query-form2">
                  <Col span="8">
                    <FormItem label="任务状态：">
                      <Select v-model="form1.taskDate">
                        <Option value="1">当前</Option>
                        <Option value="0">已到期</Option>
                        <Option value="2">未到期</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="排查日期：">
                      <DatePicker type="daterange" v-model="dateRange" format="yyyy-MM-dd" placement="bottom-end" placeholder="请选择排查日期范围" style="width:100%" ></DatePicker>
                    </FormItem>
                  </Col>
                    <i-col span="8">
                        <FormItem label="任务名称：">
                            <Input v-model="form1.taskName" placeholder="请输入任务名称"/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row class="query-form2">
                  <i-col span="8">
                    <FormItem label="排查岗位：">
                      <Input v-model="form1.screenPositionName" placeholder="请输入排查岗位"/>
                    </FormItem>
                  </i-col>
<!--                    <i-col span="8">-->
<!--                        <FormItem label="排查公司：">-->
<!--                            <Input v-model="form1.screenOrgName" placeholder="请输入机构名称"/>-->
<!--                        </FormItem>-->
<!--                    </i-col>-->
                    <i-col span="8">
                        <FormItem label="所属部门：">
                            <Input v-model="form1.department" placeholder="请输入机构名称"/>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <div style="float: right;">
                            <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
                        </div>
                    </i-col>
                </Row>
            </div>
        </Form>
        <Row class="query-form">
            <i-col span="24">
                <Button size="large" type="success" class="ivu-btn-add" icon="md-add" @click="addInfo">新增 </Button>
                <Button size="large" type="error" class="ivu-btn-add" icon="md-remove" @click="batchDelete">批量删除</Button>
            </i-col>
        </Row>
        <Table ref='table'  :loading="loading" size="small" :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change="selectionRow" @on-sort-change="querySort"
               highlight-row stripe border :columns="columns1" width="100%" :data="dataTable">
        </Table>

        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <Modal title="任务" :transfer=false v-model="model1" :width=900>
            <Form ref="dataForm" :model="dataForm" label-position="top" :rules="ruleCustom">
                <Row type="flex" justify="space-around" class="code-row-bg">
                     <Col span="11">
                        <FormItem label="排查岗位：" prop="screenPositionId">
                            <Input type="text" readonly @on-focus="openModelModal" v-model="dataForm.screenPositionName"></Input>
                            <Input type="text" v-show="false" v-model="dataForm.screenPositionId"></Input>
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="任务名称：" prop="taskName">
                            <Input type="text" v-model="dataForm.taskName"/>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="排查日期：" prop="taskDate">
                            <DatePicker type="date" style="width: 100%" format="yyyy-MM-dd"
                                        v-model="dataForm.taskDate"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="11">

                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' :loading="buttonLoading" @click="saveData()">确定</Button>
                <Button class='ivu-btn-cancel' @click="handleCancel" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>

        <Modal title="任务" :transfer=false v-model="viewModal" :width=900>
            <Form ref="viewForm" :model="viewForm" :label-width="100">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="检查岗位：">
                            {{viewForm.screenPositionName}}
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="任务名称：">
                            {{viewForm.taskName}}
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="detail-background-clor">
                    <Col span="11">
                        <FormItem label="检查日期：">
                            {{viewForm.taskDate}}
                        </FormItem>
                    </Col>
                    <Col span="11">

                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="viewModal=false">关闭</Button>
            </div>
        </Modal>

        <Modal :transfer=false footer-hide v-model="selectModelModal" :width=900>
            <ApsgItemPlanForSelect @getSelectModelData="getSelectModelData"></ApsgItemPlanForSelect>
        </Modal>

    </layout>
</template>

<script>
    import {Api} from '../../../api/index.js'
    import cascaderPosition from '../../../components/cascader-position'
    import cascaderDom from '../../../components/cascader-dom'
    import {sessionStorage} from '../../../common/cacheUtils.js';
    import ApsgItemPlanForSelect from './apsgItemPlanForSelect.vue'

    export default {
        components:{
            cascaderDom,
            cascaderPosition,
            ApsgItemPlanForSelect
        },
        data() {
            return {
                dateRange:["",""],
                currentUserPositionId:"",
                currentUserId: "",
                loginId:"",
                switchFlag : false,
                currentDate:'',
                form1: {
                    taskDate:'1',
                    taskStatus:'1'
                },
                dataForm: {},
                currentScreenOrgId: '',
                currentScreenOrgName: '',
                setCurrentScreenPositionName: {},
                //分页参数
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                columns1: [
                    {
                        width: 60,
                        align: "center",
                        fixed: 'left',
                        type: 'selection'
                    },
                    {
                        minWidth: 220,
                        title: '任务名称',
                        key: 'taskName',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '排查日期',
                        key: 'taskDate',
                        align: 'center',
                        sortable: 'custom',
                        render: (h, params) => {
                            return h('span', this.formatDate(new Date(params.row.taskDate),"yyyy-MM-dd"));
                        }
                    },
                    {
                        minWidth: 230,
                        title: '排查公司',
                        key: 'screenOrgName',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '排查岗位',
                        key: 'screenPositionName',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '排查人',
                        key: 'screenUserName',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '所属部门',
                        key: 'department',
                        align: 'center',
                        render: (h, params) => {
                                return h('span', params.row.department != ''&& params.row.department? params.row.department: params.row.screenOrgCompanyName )
                        }
                    },
                    {
                        minWidth: 130,
                        title: '排查周期',
                        key: 'plan.checkCycle',
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.plan.checkCycle == '1') {
                                return h('span', '年度')
                            } else if (params.row.plan.checkCycle == '2') {
                                return h('span', '每天')
                            } else if (params.row.plan.checkCycle == '3') {
                                return h('span',  '工作日')
                            }  else if (params.row.plan.checkCycle[0] == '5') {
                                return h('span',  '自定义')
                            } else if (params.row.plan.checkCycle == '8') {
                                return h('span', '双周')
                            } else if (params.row.plan.checkCycle == '6') {
                                return h('span',  '月度')
                            } else if (params.row.plan.checkCycle == '7') {
                                return h('span',  '季度')
                            } else if (params.row.plan.checkCycle == '4') {
                                return h('span',  '半年')
                            }
                        }
                    },
                    {
                        minWidth: 130,
                        title: '排查状态',
                        key: 'taskStatus',
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.taskStatus == '已排查') {
                                return h('span', '已排查')
                            } else {
                                return h('span', '未排查')
                            }
                        }
                    },
                    // {
                    //     minWidth: 180,
                    //     title: '排查结果描述',
                    //     key: 'taskResultDesc',
                    //     align: 'center'
                    // },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        minWidth: 200,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.viewData(params.row);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( params.row.taskStatus == '已排查') ? '#d0d0d0' :'',
                                        pointerEvents: (params.row.taskStatus == '已排查') ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.toTakeTask(params.row);
                                        }
                                    }
                                }, '执行'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (params.row.taskStatus == '已排查'||(( this.currentUserId != params.row.createUserId && this.loginId != this.Common.admin)&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                            &&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) == undefined) )   ? '#d0d0d0' : '',
                                        pointerEvents: (params.row.taskStatus == '已排查' ||((this.currentUserId != params.row.createUserId && this.loginId != this.Common.admin) && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                            &&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) == undefined) ) ?'none':''
                                    },
                                    on: {
                                        click: () => {
                                            this.toEdit(params.row);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (params.row.taskStatus != '已排查' || ((this.currentUserId != params.row.createUserId &&this.loginId != this.Common.admin)&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                            &&(sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) == undefined)) ) ? '#d0d0d0' :'red',
                                        pointerEvents: (params.row.taskStatus != '已排查' || ((this.currentUserId != params.row.createUserId &&this.loginId != this.Common.admin)&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                            &&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) == undefined))  ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params.row);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                ruleCustom: {
                    taskName: [{required: true, message: '  ', trigger: 'blur,change'}],
                    taskDate: [{required: true, message: '  ', trigger: 'blur,change', type: 'date'}],
                    checkType: [{required: true, message: '  ', trigger: 'blur,change'}],
                    checkLevel: [{required: true, message: '  ', trigger: 'blur,change'}],
                    execUserId: [{required: true, message: '  ', trigger: 'blur,change'}],
                    checkedOrg: [{required: true, message: '  ', trigger: 'blur,change'}],
                    notes: [{required: true, message: '  ', trigger: 'blur,change'}],
                },
                selectModelModal: false,
                currentCheckedOrgId: '',
                currentCheckedOrgName: '',
                currentExecOrgId: '',
                currentExecOrgName: '',
                dataTable: [],
                model1: false,
                lastDaysDisabled: true,
                add: false,
                loading: false,
                tableHeight: '',
                deleteRows: [],
                buttonLoading: false, viewModal: false,
                viewForm: {},
                viewSpanShow: false,
                viewCheckCycleRadio: '',
                viewCheckCycleCheckbox: [],
                setCurrentExecName: {},
                deleteRow: []
            }
        },
        mounted: function () {
            this.currentDate = this.formatDate(new Date(),'yyyy-MM-dd');
            if(sessionStorage('userId').getObject('userId').position != null){
                this.currentUserPositionId = sessionStorage('userId').getObject('userId').position.positionId;
            }
            this.currentUserId = sessionStorage('userId').getObject('userId').userId;
            this.loginId = sessionStorage('userId').getObject('userId').loginId;
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.query();
        },
        methods: {
            switchQuery(flag){
                this.switchFlag = flag;
                if(this.switchFlag){
                    this.tableHeight = this.tableHeight - 88;
                }else{
                    this.tableHeight = this.tableHeight + 88;
                }
            },
            rowClassName (row, index) {
                if (row.taskStatus === "1") {
                    return 'table-info-row-before-day';
                } else if (row.taskStatus === "2") {
                    return 'table-error-row-current-day';
                } else if (row.taskStatus === "3") {
                    return 'table-error-row-atfer-day';
                }
                return '';
            },
            getSelectModelData(row) {
                this.dataForm.screenPositionId = row.postId;
                this.dataForm.screenPositionName = row.postName;
                this.dataForm.itemPlanId = row.id;
                this.dataForm.taskName = row.postName +  '单次排查任务';
                this.selectModelModal = false;
            },
            openModelModal() {
                this.selectModelModal = true;
            },
            handleCancel() {
                this.model1 = false;
            },

            setExecOrgId(data) {
                this.dataForm.execOrgId = data[data.length - 1];
            },
            setExecOrgName(data) {
                this.dataForm.execOrgName = data;
            },

            setCheckedOrgId(data) {
                this.dataForm.checkedOrg = data[data.length - 1];
            },
            setCheckedOrgName(data) {
                this.dataForm.checkedOrgName = data;
            },

            addInfo() {
                this.dataForm = {};
                this.currentScreenOrgName = '';
                this.currentScreenOrgId = '';
                this.currentExecOrgId = '';
                this.currentExecOrgName = '';
                this.setCurrentExecName = {};
                this.model1 = true;
            },

            setExecUserName(data) {
                this.dataForm.execUserName = data;
            },
            setExecUserId(data) {
                this.dataForm.execUserId = data[data.length - 1];
            },

            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },

            toEdit(row) {
                this.model1 = true;
                this.dataForm = JSON.parse(JSON.stringify(row));
                this.dataForm.taskDate = this.formatDate(new Date(this.dataForm.taskDate), 'yyyy-MM-dd');
            },
            viewData(row) {
                    this.viewForm = row;
                    this.viewForm.taskDate = this.formatDate(new Date(this.viewForm.taskDate),"yyyy-MM-dd")
                    this.viewModal = true;
            },
            saveData() {
                this.$refs.dataForm.validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        this.dataForm.taskDate = this.formatDate(new Date(this.dataForm.taskDate), 'yyyy-MM-dd');
                        this.$http.post(Api.saveOrUpdateApsgTask, this.dataForm).then((res) => {
                            this.$Message.success("保存成功")
                            this.model1 = false;
                            this.query();
                            this.buttonLoading = false
                        }).catch(e => {
                            this.model1 = false;
                            this.query();
                            this.buttonLoading = false
                            this.$Message.error("数据保存失败")
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            toTakeTask(row){
                this.modalName = '新增';
                this.$router.push({path:'/hidHazardDetail',query: {isUpdate: 'false',generateType:'2', taskId:row.taskId, itemPlanId: row.itemPlanId}});
            },
            query() {
                let roleId = '';
                if(sessionStorage('userId').getObject('userId').userRole != null )
                    sessionStorage('userId').getObject('userId').userRole.map((i=>{
                        if(i.roleId == '73b38b37dff64392ba0ee7dd579bf293') roleId = i.roleId;
                    }));
                this.loading = true;
                if (this.dateRange[0]!=""&&this.dateRange[1]!=""){
                    this.form1.startDate =  this.formatDate(new Date(this.dateRange[0]), 'yyyy-MM-dd');
                    this.form1.endDate = this.formatDate(new Date(this.dateRange[1]), 'yyyy-MM-dd');
                }
                let data = {
                    currentPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    userId: sessionStorage('userId').getObject('userId').userId,
                    orgId: sessionStorage('userId').getObject('userId').companyId,
                    roleId: roleId
                }
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
                let url = Api.getTaskDataList;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            reset() {
                this.form1 = {};
                this.query();
            },

            deleteData(row) {
                let _this = this;
                let config = {
                    title: '系统提示',
                    content: '确认删除选中数据吗?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: function () {
                        _this.$Spin.show({
                            render: (h) => {
                                return h('div', [
                                    h('Icon', {
                                        'class': 'demo-spin-icon-load',
                                        props: {
                                            type: 'ios-loading',
                                            size: 18
                                        }
                                    }),
                                    h('div', 'Loading')
                                ])
                            }
                        });
                        let url = Api.deleteApsgTaskById + '/' + row.taskId;
                        this.$http.delete(url).then((res) => {
                            _this.$Message.success('删除成功');
                            _this.query();
                            _this.$Spin.hide();
                        }).catch(e => {
                            _this.$Spin.hide();
                            _this.$Message.error('删除失败' + e);
                        })
                    },
                    onCancel: function () {
                    }
                }
                this.$Modal.confirm(config);
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            compareDate(dateTime1,dateTime2)
            {
                var formatDate1 = new Date(dateTime1);
                var formatDate2 = new Date(dateTime2);
                if(formatDate1 < formatDate2)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            },
            selectionRow(selection){
                this.deleteRow = selection;
                console.log(this.deleteRow);
            },

            batchDelete(){
                if(this.deleteRow.length == 0){
                    this.$Message.error({ content: '请至少选择一条数据！', duration: 4 });
                    return;
                }
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>确定批量删除该数据？</p>',
                    onOk: () => {
                        let ids = '';
                        this.deleteRow.forEach(item=>{
                            ids += item.taskId + ',';
                        })
                        this.$http.put(Api.deleteApsgTaskById +'/batch/delete', {taskId: ids}).then((res) => {
                            this.$Message.success({ content: '删除成功', duration: 4 });
                            this.query();
                        }).catch(e => {
                            this.$Message.error({ content: '删除失败', duration: 4 });
                        })
                    },
                    onCancel: () => {
                    }
                });
            },
            querySort({column, key, order}){
              this.pagedata.currentPage = 1;
              this.form1.order = order;
              this.form1.key = key;
              this.query()
            },
        },
    }
</script>
<style lang='css'>
    @import './../../../index.css';


    .ivu-table .table-info-row-before-day td{
        background-color: #2db7f5;
        color: #fff;
    }

    .ivu-table .table-info-row-current-day td{
        background-color: #ff6600;
        color: #fff;
    }

    .ivu-table .table-info-row-after-day td{
        background-color: #aacc00;
        color: #fff;
    }

</style>
